import NProgress from "nprogress";
import "nprogress/nprogress.css"; // progress bar style
import { userStore } from "@/store/module/user";
import router from "@/router/index.js";
/**
 * 权限配置
 * 路由跳转中，页面载入进度条
 * @author Dujh
 * @time 2023/4/13
 */
NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 白名单路由，不需要登录即可访问
const WHITE_LIST = ["login", "NotFound"];

router.beforeEach(async (to, from, next) => {
  try {
    NProgress.start();

    // 判断是否已登录并访问登录页，重定向到首页
    if (to.name === "login" && userStore().isAuthenticated) {
      next({ path: "/layout/home" });
      NProgress.done();
      return;
    }

    const hasPermission = await checkPermission(to);

    if (hasPermission) {
      next();
    } else {
      // 无权限，重定向到登录页，并记录当前路由以便登录后返回
      next({
        name: "login",
        query: { redirect: to.fullPath },
      });
    }
  } catch (error) {
    console.error("权限检查异常:", error);
    NProgress.done();
    next(false);
  }
});

// 路由权限检查
const checkPermission = async (to) => {
  const store = userStore();
  // 检查是否需要认证
  if (!to.meta?.requiresAuth || WHITE_LIST.includes(to.name)) {
    return true;
  }
  // 已登录
  if (store.isAuthenticated) {
    // 如果没有用户信息，尝试获取用户信息
    if (!store.user) {
      try {
        await store.fetchUser();
      } catch (error) {
        console.error("获取用户信息失败:", error);
        store.logout();
        return false;
      }
    }
    return true;
  }
  return false;
};
router.afterEach(() => {
  NProgress.done();
});
